<template>
    <div style="width:90%;margin:20px 4%;">
        <div style="text-align: left;margin:10px 10px;">
            <h2>您好，{{userInfo.userName}}！欢迎登录健康管理系统！</h2>
        </div>
        <div style="margin:20px 0">
            <el-row :gutter="20">
                <el-col :span="14">
                    <el-card class="box-card">
                        <el-row>
                            <el-col :span="4">
                                <el-avatar
                                        :src="userInfo.avatar"
                                        :size="90"
                                        style="margin-top: 20px"
                                        @click="updateAvatar"
                                />
                            </el-col>
                            <el-col :span="20">
                                <div style="display: flex;justify-content: space-between">
                                    <el-divider content-position="left">基本信息</el-divider>
                                    <el-button class="button" type="primary" @click="edit"><el-icon><Edit /></el-icon>编辑</el-button>
                                </div>
                                <el-descriptions>
                                    <el-descriptions-item label="用户名">{{userInfo.userName}}</el-descriptions-item>
                                    <el-descriptions-item label="手机号">{{userInfo.userPhone}}</el-descriptions-item>
                                    <el-descriptions-item label="角色">
                                        <el-tag size="small" v-if="userInfo.userRole=='A'">管理员</el-tag>
                                        <el-tag size="small" v-else>普通用户</el-tag>
                                    </el-descriptions-item>
                                </el-descriptions>
                                <div style="display: flex;justify-content: space-between">
                                    <el-divider content-position="left">个人档案</el-divider>
                                    <el-button class="button" type="primary" @click="keepArchives"><el-icon><Finished /></el-icon>查看</el-button>
                                </div>
                            </el-col>
                        </el-row>
                    </el-card>
                    <el-card style="width:100%;margin-top: 20px">
                        <div>
                            <el-tabs v-model="activeName" @tab-click="handleClick">
                                <el-tab-pane label="修改密码" name="first">
                                    <el-form ref="pwdRules" :model="checkPwd" :rules="pwdRules" label-width="80px">
                                        <el-form-item label="旧密码" prop="oldPassword">
                                            <el-input v-model="checkPwd.oldPassword" placeholder="请输入旧密码" type="password" show-password/>
                                        </el-form-item>
                                        <el-form-item label="新密码" prop="newPassword">
                                            <el-input v-model="checkPwd.newPassword" placeholder="请输入新密码" type="password" show-password/>
                                        </el-form-item>
                                        <el-form-item label="确认密码" prop="confirmPassword">
                                            <el-input v-model="checkPwd.confirmPassword" placeholder="请确认新密码" type="password" show-password/>
                                        </el-form-item>
                                        <el-form-item>
                                            <el-button type="primary" size="mini" @click="submit">保存</el-button>
                                            <!--                      <el-button type="danger" size="mini" @click="close">关闭</el-button>-->
                                        </el-form-item>
                                    </el-form>
                                </el-tab-pane>
                                <!--                                <el-tab-pane label="修改邮箱" name="second">暂未开发</el-tab-pane>-->

                            </el-tabs>
                        </div>
                    </el-card>

                </el-col>
                <el-col :span="10">
                    <el-card style="width:100%;">
                        <div>
                            <el-calendar>
                            </el-calendar>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <!--基本信息修改-->
        <el-dialog title="基本信息修改" v-model="open" width="600px" append-to-body destroy-on-close>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户名" prop="userName">
                            <el-input v-model="form.userName" placeholder="请填写用户名" maxlength="30" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="userPhone">
                            <el-input v-model="form.userPhone" placeholder="请填写手机号" maxlength="11" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: right">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog v-model="addImgDialog" title="更新头像" width="20%">
            <el-upload
                    class="avatar-uploader"
                    :action="uploadPath"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
            >
                <img v-if="newImg" :src="newImg" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <span>
              图片大小限制2M，格式png/jpg
            </span>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="closeUploadImg">取消</el-button>
                <el-button type="warning" @click="ConfirmUploadImg">
                    确定
                </el-button>
              </span>
            </template>
        </el-dialog>

        <el-drawer
                ref="drawerRef"
                v-model="dialog2"
                title="个人健康档案"
                direction="rtl"
                class="demo-drawer"
        >
            <div style="padding: 10px 20px">
                <el-card class="box-card" style="text-align: left;line-height: 35px;margin: 20px 0px">
                    <h3>体检档案详情</h3>
                    <p><el-icon><Location /></el-icon>档案管理中心</p>
                    <p style="color: #b9170b"><el-icon><WarningFilled /></el-icon>档案含有用户隐私，不得泄露，泄露后果自负！</p>
                </el-card>

                <el-card class="box-card" style="text-align: left;line-height: 35px">
                    <el-descriptions title="档案管理" column="2">
                        <el-descriptions-item label="档案编号"><h2>{{detail.archiveNumber}}</h2></el-descriptions-item>
                        <el-descriptions-item label="姓名">{{detail.userName}}</el-descriptions-item>
                        <el-descriptions-item label="联系电话">{{detail.userPhone}}</el-descriptions-item>
                        <el-descriptions-item label="证件号">{{detail.idCard}}</el-descriptions-item>
                        <el-descriptions-item label="性别">{{detail.gender}}</el-descriptions-item>
                        <el-descriptions-item label="身高">{{detail.height}}</el-descriptions-item>
                        <el-descriptions-item label="血型">{{detail.bloodType}}</el-descriptions-item>
                        <el-descriptions-item label="过敏情况">{{detail.allergies}}</el-descriptions-item>
                        <el-descriptions-item label="过往病史">{{detail.medicalHistory}}</el-descriptions-item>
                        <el-descriptions-item label="在服药物">{{detail.medication}}</el-descriptions-item>
                        <el-descriptions-item label="档案录入时间">
                            {{ $filters.formatDate(detail.createTime) }}
                        </el-descriptions-item>
                        <el-descriptions-item label="档案更新时间">
                            {{ $filters.formatDate(detail.updateTime) }}
                        </el-descriptions-item>
                        <el-descriptions-item label="饮食方案">
                            <el-button
                                    @click="keeps(1)"
                                    style="color: #ffb70d"
                                    :link="true"
                            ><el-icon><Pointer /></el-icon>查看
                            </el-button>
                        </el-descriptions-item>
                        <el-descriptions-item label="用药方案">
                            <el-button
                                    @click="keeps(2)"
                                    style="color: #ffb70d"
                                    :link="true"
                            ><el-icon><Pointer /></el-icon>查看
                            </el-button>
                        </el-descriptions-item>
                    </el-descriptions>
                    <div style="padding: 0px 30px;position: relative;float: right;padding: 10px 20px">
                        <el-button type="success" @click="cancelArchives">关闭</el-button>
                    </div>
                </el-card>
            </div>
        </el-drawer>
<!--饮食方案以及用药方案-->
        <el-drawer
                ref="drawerRef"
                v-model="dialog3"
                :title="title1"
                direction="ltr"
                class="demo-drawer"
        >
            <div style="padding: 10px 20px">
                <el-card class="box-card" style="text-align: left;line-height: 35px;margin: 20px 0px">
                    <h3>健康管理平台</h3>
                    <p style="color: #1dc355"><el-icon><WarningFilled /></el-icon>时刻做一个自律的人！</p>
                </el-card>

                <el-card class="box-card" style="text-align: left;line-height: 35px">
                    <el-descriptions :title="title1" column="1" v-if="this.title1==='饮食方案'">
                        <el-descriptions-item label="档案编号"><h2>{{programme.archiveNumber}}</h2></el-descriptions-item>
                        <el-descriptions-item label="方案名称">{{programme.dietName}}</el-descriptions-item>
                        <el-descriptions-item label="方案内容">{{programme.dietContent}}</el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions :title="title1" column="1" v-else>
                        <el-descriptions-item label="档案编号"><h2>{{programme.archiveNumber}}</h2></el-descriptions-item>
                        <el-descriptions-item label="方案名称">{{programme.medicineName}}</el-descriptions-item>
                        <el-descriptions-item label="方案内容">{{programme.medicineContent}}</el-descriptions-item>
                    </el-descriptions>
                    <div style="padding: 0px 30px;position: relative;float: right;padding: 10px 20px">
                        <el-button type="success" @click="dialog3=false">关闭</el-button>
                    </div>
                </el-card>
            </div>
        </el-drawer>
    </div>
</template>

<script>
    export default {
        components: {},
        props: {},
        data() {
            return {
                title1:'饮食方案',
                programme:{},//方案
                dialog3:false,
                dialog2:false,
                detail:{},//个人健康档案
                uploadPath:'http://127.0.0.1:8086/upload',
                newImg:'',
                addImgDialog:false,
                form:{},
                open:false,
                checkPwd:{
                    oldPassword:'',
                    newPassword:'',
                    confirmPassword:'',
                },
                activeName:'first',
                userInfo:{},
                rules: {
                    userName: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min:2,max: 5, message: '铺分类名称需在2~5个字符', trigger: 'blur'},
                    ],
                    userPhone: [
                        { required: true, message: "请输入手机号", trigger: "blur" },
                        {
                            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                            message: "请输入正确的手机号码",
                            trigger: "blur"
                        }
                    ],
                },
                pwdRules:{
                    oldPassword:[
                        { required: true, message: "请输入原密码！", trigger: "blur" },
                        {
                            pattern: '^\\d{6,12}$',
                            message: "只能由6~12位数字组成！",
                            trigger: "blur"
                        }
                    ],
                    newPassword:[
                        { required: true, message: "请输入新密码！", trigger: "blur" },
                        {
                            pattern: '^\\d{6,12}$',
                            message: "只能由6~12位数字组成！",
                            trigger: "blur"
                        }
                    ],
                    confirmPassword:[
                        { required: true, message: "请确认密码！", trigger: "blur" },
                        {
                            pattern: '^\\d{6,12}$',
                            message: "只能由6~12位数字组成！",
                            trigger: "blur"
                        },
                        {
                            validator:this.validateConfirmPassword,trigger:'blur'
                        }
                    ],
                },
            };
        },
        watch: {},
        computed: {},
        methods: {
            async keeps(num) {
                // console.log(num)
                // console.log(this.detail.archiveNumber)
                if (num === 1) {
                    this.title1="饮食方案";
                    const {data: res} = await this.$http.get("diet/getHealthDietsByArchiveNumber", {
                        params: {
                            archiveNumber: this.detail.archiveNumber,
                        }
                    });
                    console.log(res)
                    if (res.code===200){
                        this.programme=res.data;
                        this.dialog3 = true;
                    }else{
                        this.$message.error("您还未生成饮食方案！")
                    }
                } else {
                    this.title1="用药方案";
                    const {data: res} = await this.$http.get("medicine/getHealthMedicineByArchiveNumber", {
                        params: {
                            archiveNumber: this.detail.archiveNumber,
                        }
                    });
                    console.log(res)
                    if (res.code===200){
                        this.programme=res.data;
                        this.dialog3 = true;
                    }else{
                        this.$message.error("您还未生成用药方案！")
                    }
                }

            },
            cancelArchives(){
              this.dialog2=false;
            },
            //查看个人档案
            async keepArchives() {
                const {data: res} = await this.$http.get("archives/getArchivesByUserId");
                console.log(res)
                if (res.data!=null){
                    this.detail=res.data;
                    this.dialog2=true;
                }else {
                    this.$message.error("您还未生成档案！");
                }
            },
            cancel(){
                this.form={};
                this.open=false;
            },
            updateAvatar(){
                this.newImg=this.userInfo.avatar;
                this.addImgDialog=true;
            },
            closeUploadImg(){
                if (this.newImg!=this.user.avatar){
                    this.$http.get("/deleteFile",{
                        params:{
                            imgUrl:this.newImg,
                        }
                    });
                }
                this.addImgDialog=false;
            },
            //更新图片地址
            async ConfirmUploadImg() {
                const {data: res} = await this.$http.get("user/updateImgUrl", {params:{
                        imgUrl:this.newImg,
                        id:this.userInfo.id,
                    }});
                if (res.code==200){
                    this.getUser();
                    this.addImgDialog=false;
                    this.$message.success("头像更新成功！")
                }else {
                    this.$message.error("服务器异常，请稍后再试！")
                }
            },
            //上传成功前回调
            beforeAvatarUpload(file){
                if (file.type !== 'image/jpg' && file.type!=='image/png') {
                    this.$message.error('图片只能是jpg/png格式！')
                    return false
                } else if (file.size / 1024 / 1024 > 2) {
                    this.$message.error('图片大小不能超过2M！')
                    return false
                }
                return true
            },
            //上传成功的回调
            handleAvatarSuccess(file){
                console.log("--------------")
                this.newImg=file.data;
                console.log(this.newImg)
            },
            /** 提交按钮 */
            async submitForm() {
                console.log(this.form)
                await this.$refs["form"].validate(async valid => {
                    if (valid) {
                        const {data:res}=await this.$http.post("user/updateUser",this.form);
                        if (res.code==200){
                            this.getUser();
                            this.$message.success('修改成功')
                        }else if(res.code==50003){
                            this.$message.error('用户手机号码已存在!')
                        }else {
                            this.$message.error('服务器异常!')
                        }
                    }
                });
                this.open = false
            },
            edit(){
                this.form=this.userInfo;
                this.open=true;
            },
            // 确认密码校验
            validateConfirmPassword(rule, value, callback) {
                if (value === '') {
                    callback(new Error('请请再次输入新密码'));
                } else if (value !== this.checkPwd.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            },
            //密码修改
            async submit() {
                await this.$refs["pwdRules"].validate(async valid => {
                    if (valid) {
                        const {data: res} = await this.$http.get("user/updatePassword", {params:this.checkPwd});
                        if (res.code == 200) {
                            this.$router.push("/");//跳转到登录页重新登录
                            this.$message.success('密码修改成功')
                        } else if (res.code == 50010) {
                            this.$message.error('原密码输入有误！')
                        } else {
                            this.$message.error('服务器异常!')
                        }
                    }
                });
            },
            // 切换框点击事件
            handleClick(tab, event) {
                console.log(tab, event);
            },
            //获取用户信息
            getUser(){
                this.$http.get("user/getUserById").then((res)=>{
                    console.log(res)
                    this.userInfo=res.data.data;
                })
            },
        },
        created() {
        },
        mounted() {
            this.getUser();
        }
    };
</script>
<style scoped>
    .avatar-uploader .avatar {
        width: 120px;
        height: 120px;
        display: block;
    }
</style>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        text-align: center;
    }
</style>